package com.zhuiYun.project.config.loginhandler;

import com.zhuiYun.project.api.sysUser.entiy.SysUser;
import com.zhuiYun.project.api.sysUser.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName SecurityUserServiceImpl
 * @Description 用户登录
 * @Author zcy
 * @Date 2023/3/24 15:23
 **/
@Component
public class SecurityUserServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 用户登录
     * @param loginName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        if (loginName == null || "".equals(loginName)) {
            throw new RuntimeException("用户不能为空");
        }
        //根据用户名查询用户
        SysUser sysUser = sysUserService.getUserByLoginName(loginName);
        if (sysUser == null) {
            throw new UsernameNotFoundException("User " + loginName + " was not found in db");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
//        if (sysUser != null) {
//            //获取该用户所拥有的权限
//            List<SysPermission> sysPermissions = sysPermissionService.selectListByUser(sysUser.getId());
//            // 声明用户授权
//            sysPermissions.forEach(sysPermission -> {
//                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
//                grantedAuthorities.add(grantedAuthority);
//            });
//        }
        return new User(sysUser.getLoginName(), sysUser.getPassword(),grantedAuthorities);
    }
}
